import { defineStore } from "pinia";
import type { RouteRecordRaw } from "vue-router";
import { Session, Local } from "@/utils/storage";
import { login, logout } from "@/api/auth";

// 保存到 Local 或 Session 的 key
export const Key = {
    rememberKey: "isRemember",
    accessTokenKey: "accessToken",
    userInfoKey: "userInfo",
};

// 用户所拥有的路由权限
export const useAuthStore = defineStore("auth", {
    state: (): AuthState<RouteRecordRaw> => {
        return {
            rememberData: Local.get(Key.rememberKey),
            accessToken: Session.get(Key.accessTokenKey),
            userInfo: Session.get(Key.userInfoKey),
            buttonList: [],
            menuList: [],
        };
    },
    actions: {
        // 记住密码
        setRememberPwd(data?: LoginData) {
            this.rememberData = data;
            if (data) {
                Local.set(Key.rememberKey, {
                    username: data.username,
                    password: data.password,
                });
            } else {
                Local.remove(Key.rememberKey);
            }
        },
        // 登录
        userLogin(loginData: LoginData) {
            return new Promise((resolve, reject) => {
                login(loginData)
                    .then((res) => {
                        const { data } = res;
                        // 状态赋值
                        const { access_token } = data;
                        this.accessToken = access_token;
                        // 保存到 Session 中
                        Session.set(Key.accessTokenKey, access_token);
                        // 正常响应钩子
                        resolve(res);
                    })
                    .catch((err) => {
                        reject(err); // 异常
                    });
            });
        },
        // 更新用户信息
        async setUserInfo(data: UserInfo) {
            this.userInfo = data;
            Session.set(Key.userInfoKey, data);
        },
        // 更新按钮权限
        async setButtonList(data: string[]) {
            this.buttonList = data;
        },
        // 更新菜单权限
        async setMenuList(data: RouteRecordRaw[]) {
            this.menuList = data;
        },
        // 退出系统
        userLogout() {
            return new Promise((resolve, reject) => {
                logout().then((res:any) => {
                    // 重置状态
                    this.resetUserState();
                    // 重新加载当前页，需认证页面会去登录页
                    window.location.reload();
                    resolve(res);
                }).catch((err:Error) => {
                    reject(err);
                })
            })
        },
        // 重置状态
        resetUserState() {
            this.menuList = [];
            this.accessToken = undefined;
            this.userInfo = undefined;
            // 清除缓存
            Session.remove(Key.accessTokenKey)
            Session.remove(Key.userInfoKey)
        },
    },
});
